<?php

namespace app\system\controller\system;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;


class Translate extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['cn', 'ko', 'en'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\system\Translate;
    }


    /**
     * 导出语言包
     */
    public function exportLanguage(){
        $result = db::name('translate')->field('cn, ko, en')->order('id asc')->select();
        $q_cn = "/**\n* 全局公共语言包\n* 覆盖风险：请避免使用页面语言包的目录名、文件名作为翻译 key\n*/\nexport default { \n";
        $h_cn = "<?php\nreturn [\n";
        $q_ko = "/**\n* 全局公共语言包\n* 覆盖风险：请避免使用页面语言包的目录名、文件名作为翻译 key\n*/\nexport default { \n";
        $h_ko = "<?php\nreturn [\n";
        $q_en = "/**\n* 全局公共语言包\n* 覆盖风险：请避免使用页面语言包的目录名、文件名作为翻译 key\n*/\nexport default { \n";
        $h_en = "<?php\nreturn [\n";
        foreach($result as $val){
            $q_cn .= "\t'{$val['cn']}': '{$val['cn']}', \n";
            $h_cn .= "\t'{$val['cn']}' => '{$val['cn']}', \n";
            if($val['ko']) $q_ko .= "\t'{$val['cn']}': '" . html_entity_decode($val['ko']) . "', \n";
            if($val['ko']) $h_ko .= "\t'{$val['cn']}' => '" . html_entity_decode($val['ko']) . "', \n";
            if($val['en']) $q_en .= "\t'{$val['cn']}': '{$val['en']}', \n";
            if($val['en']) $h_en .= "\t'{$val['cn']}' => '{$val['en']}', \n";
        }

        $q_cn .= "}";
        $q_ko .= "}";
        $q_en .= "}";
        $h_cn .= "];";
        $h_ko .= "];";
        $h_en .= "];";

        $data = [
            'q_cn' => $q_cn,
            'h_cn' => $h_cn,
            'q_ko' => $q_ko,
            'h_ko' => $h_ko,
            'q_en' => $q_en,
            'h_en' => $h_en
        ];
        $this->success('', $data);

        echo $h_cn;
    }


    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where);
        $param = $this->request->param();

        if(!empty($param['type'])){
            $res = $res->where('FIND_IN_SET(:value,type)',['value' => $param['type']]);
        }

        $res = $res->order($order)->paginate($limit);

        $list = $res->items();

        foreach($list as $key => $val){
            $list[$key]['ko'] = empty($val['ko']) ? null : html_entity_decode($val['ko']);
        }

        $last_time = db::name('translate')->order('update_time desc')->find();

        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
            'update_time' => date('Y-m-d H:i:s', $last_time['update_time']),
        ]);
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }


            if(empty($data['cn'])) $this->error('请输入中文');

            $translate = db::name('translate')->where(['cn' => $data['cn']])->find();
            if($translate) $this->error('不能重复添加该中文词汇');

            $data['admin_id'] = $this->auth->id;
            $data['create_time'] = $this->timestamp;
            $result = false;
            $this->model->startTrans();
            try {

                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }



    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);

            $result = false;
            $this->model->startTrans();
            try {
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $row['ko'] = empty($row['ko']) ? null : html_entity_decode($row['ko']);

        $this->success('', [
            'row' => $row
        ]);
    }































}